package com.hxzy.service.impl;

import com.hxzy.dto.BountyOrderDto;
import com.hxzy.entity.BountyOrder;
import com.hxzy.entity.PageBean;
import com.hxzy.mapper.BountyOrderMapper;
import com.hxzy.mapper.TypeMapper;
import com.hxzy.service.BountyOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BountyOrderImplService implements BountyOrderService {

    @Autowired
    private BountyOrderMapper bountyOrderMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Override
    public void updateStatus(Long id, int status) {
        int status1 = status==0 ? 1 : 0;
        bountyOrderMapper.updateStatus(id,status1);
    }


    @Override
    public List<BountyOrder> selectAll() {
        return bountyOrderMapper.selectAll();
    }

    @Override
    public boolean insertBounty(BountyOrder bountyOrder) {
        int i = bountyOrderMapper.insertBounty(bountyOrder);
        return i > 0;
    }

    @Override
    public boolean deleteBounty(List<Long> ids) {
        int i = bountyOrderMapper.deleteBounty(ids);
        return i >0 ;
    }

    @Override
    public BountyOrder selectById(Long id) {
        return bountyOrderMapper.selectById(id);
    }

    @Override
    public boolean updateBounty(BountyOrder bountyOrder) {
        int i = bountyOrderMapper.updateBounty(bountyOrder);
        return i>0;
    }

    @Override
    public PageBean<BountyOrderDto> selectByPageAndCondition(int currentPage, int pageSize, BountyOrder bountyOrder) {

        //1. 计算开始索引
        int begin = (currentPage - 1) * pageSize;

        //2.处理name条件，模糊表达式
        String name = bountyOrder.getName();
        if (name != null && name.length() > 0) {
            bountyOrder.setName("%" + name + "%");
        }

        //3. 查询当前页数据
        List<BountyOrder> bountyOrderList = bountyOrderMapper.selectByPageAndCondition(begin, pageSize, bountyOrder);

        //4. 查询总记录数
        int totalCount = bountyOrderMapper.selectTotalCountByCondition(bountyOrder);

        ArrayList<BountyOrderDto> bountyOrderDtoArrayList = new ArrayList<>();

        for (BountyOrder ob : bountyOrderList
             ) {
            BountyOrderDto bountyOrderDto = new BountyOrderDto();
            BeanUtils.copyProperties(ob, bountyOrderDto);
            Long typeId = ob.getTypeId();
            String typeName = typeMapper.selectById(typeId);
            bountyOrderDto.setTypeName(typeName);
            bountyOrderDtoArrayList.add(bountyOrderDto);
        }

        //5. 封装PageBean对象
        PageBean<BountyOrderDto> pageBean = new PageBean<>();
        pageBean.setRows(bountyOrderDtoArrayList);
        pageBean.setTotalCount(totalCount);
        return pageBean;
    }



}
